package com.monitor.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.monitor.dao.*;
import com.monitor.entity.*;
import com.monitor.service.ErpWarehouseService;
import com.monitor.util.BlankUtil;
import com.monitor.util.CalculationTax;
import com.monitor.util.DataUtil;
import com.monitor.util.IDUtils;
import com.monitor.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 仓库物料 数量统计表 服务实现类
 * </p>
 *
 * @author LX
 * @since 2018-09-11
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class ErpWarehouseServiceImpl extends ServiceImpl<ErpWarehouseMapper, ErpWarehouse> implements ErpWarehouseService {
	@Resource
	private ErpMaterielMapper erpMaterielMapper;
	
	@Resource
	private ErpCustomerWarehouseMapper erpCustomerWarehouseMapper;
	
	@Resource
	private ErpWarehouseMapper erpWarehouseMapper;
	
	@Resource
	private ErpMaterielFlowSummaryMapper erpMaterielFlowSummaryMapper;
	
	@Resource
	private ErpTireArchivesMapper erpTireArchivesMapper;
	
	@Resource
	private ErpTireArchivesWorkMapper erpTireArchivesWorkMapper;
	
	@Resource
	private ErpMaterielFlowMaterielMapper erpMaterielFlowMaterielMapper;
	
	@Resource
	private ErpTireSensorMapper erpTireSensorMapper;
	
	@Resource
	private ErpMaterielCopyMapper erpMaterielCopyMapper;
	
	@Resource
	private ErpCustomerMapper erpCustomerMapper;
	
	@Override
	public Result<Integer> saveMateriels(ErpMateriel materiel,Double allPrice,int custId,int materielNumber,String faPiao,String cangkuName,String jingban, String[] shengIds,String[] qrCode,String[] rfList,String custName,String taiJson,String chuanIds,String qrChuanCodes,String rfChuanIds) {
		// TODO Auto-generated method stub
		try {
			double taxNew = 0.00;
			Date workDate=new Date();
			ErpMateriel ma=null;
			if(materiel.getZhiNeng()) {
				ma=JSON.parseObject(taiJson, ErpMateriel.class);
				if(chuanIds!=null&&chuanIds.length()>0) {
					String[] chuanIds1=chuanIds.split(",");
					String str0="";
			    	for(String str:chuanIds1) {
			    		if(!str.equals("")) {
							//List<ErpMateriel> lenthList=erpMaterielMapper.selectList(new EntityWrapper<ErpMateriel>().eq("materiel_production_id", str).and().eq("delect_type", 1));
			    			List<ErpMateriel> lenthList=erpMaterielMapper.selectList(new EntityWrapper<ErpMateriel>().eq("materiel_name", ma.getMaterielName()).and().eq("materiel_brand", ma.getMaterielBrand()).and().eq("materiel_Specifications", ma.getMaterielSpecifications()).and().eq("materiel_model", ma.getMaterielModel()).and().eq("materiel_place", ma.getMaterielPlace()).and().eq("materiel_state", ma.getMaterielState()).and().eq("materiel_unit", ma.getMaterielUnit()).and().eq("materiel_production_id", str));
			    			if(lenthList.size()>0){
								str0+=str+",";
							}
							//strList.add(str);
			    		}
			    	}
			    	//List<ErpMateriel> lenthList=erpMaterielMapper.selectList(new EntityWrapper<ErpMateriel>().eq("materiel_name", materiel.getMaterielName()).and().eq("materiel_brand", materiel.getMaterielBrand()).and().eq("materiel_Specifications", materiel.getMaterielSpecifications()));
			    	if(!str0.trim().equals("")) {
			    		return new Result<>(2, "传感器生产编号重复"+str0);
			    	}
				}
			}
			if(shengIds!=null&&shengIds.length>0) {           //判断是否有这个生产编号
				//List<String> strList=new ArrayList<>();
				String str0="";
		    	for(String str:shengIds) {
		    		if(!str.equals("")) {
						//List<ErpMateriel> lenthList=erpMaterielMapper.selectList(new EntityWrapper<ErpMateriel>().eq("materiel_production_id", str).and().eq("delect_type", 1));
		    			List<ErpMateriel> lenthList=erpMaterielMapper.selectList(new EntityWrapper<ErpMateriel>().eq("materiel_name", materiel.getMaterielName()).and().eq("materiel_brand", materiel.getMaterielBrand()).and().eq("materiel_Specifications", materiel.getMaterielSpecifications()).and().eq("materiel_model", materiel.getMaterielModel()).and().eq("materiel_place", materiel.getMaterielPlace()).and().eq("materiel_state", materiel.getMaterielState()).and().eq("materiel_unit", materiel.getMaterielUnit()).and().eq("materiel_production_id", str));
		    			if(lenthList.size()>0){
							str0+=str+",";
						}
						//strList.add(str);
		    		}
		    	}
		    	//List<ErpMateriel> lenthList=erpMaterielMapper.selectList(new EntityWrapper<ErpMateriel>().eq("materiel_name", materiel.getMaterielName()).and().eq("materiel_brand", materiel.getMaterielBrand()).and().eq("materiel_Specifications", materiel.getMaterielSpecifications()));
		    	if(!str0.trim().equals("")) {
		    		return new Result<>(2, "生产编号重复"+str0);
		    	}
			}
			
		    	//判断是否含税
				int IncludingTax = 1;//未含税
				if(faPiao!=null &&faPiao.indexOf("增值")!=-1){
					IncludingTax = 0;    //含税
				}
				Boolean pan=false;
				//ErpCustomerWarehouse custWareHouse=erpCustomerWarehouseMapper.selectById(materiel.getWarehouseId());
				ErpWarehouse wareHouse=new ErpWarehouse();
				wareHouse.setCustomerId(custId);
				wareHouse.setWarehouseId(materiel.getWarehouseId());
				wareHouse.setMaterielName(materiel.getMaterielName());
				wareHouse.setMaterielBrand(materiel.getMaterielBrand());
				wareHouse.setMaterielSpecifications(materiel.getMaterielSpecifications());
				wareHouse.setMaterielModel(materiel.getMaterielModel());
				wareHouse.setMaterielPlace(materiel.getMaterielPlace());
				wareHouse.setMaterielState(materiel.getMaterielState());
				wareHouse.setMaterielUnit(materiel.getMaterielUnit());
				ErpWarehouse ware=erpWarehouseMapper.selectWareHouse(wareHouse);
				if(ware==null) {                   //判断仓库里是否存在该物料  等于null为不存在
					pan=true;
					ware = new ErpWarehouse();           //仓库表里添加一条物料信息
					ware.setCustomerId(custId);
					ware.setWarehouseId(materiel.getWarehouseId());
					ware.setMaterielName(materiel.getMaterielName());
					ware.setMaterielBrand(materiel.getMaterielBrand());
					ware.setMaterielSpecifications(materiel.getMaterielSpecifications());
					ware.setMaterielModel(materiel.getMaterielModel());
					ware.setMaterielPlace(materiel.getMaterielPlace());
					ware.setMaterielState(materiel.getMaterielState());
					ware.setMaterielUnit(materiel.getMaterielUnit());
					ware.setMaterielNumber(materiel.getMaterielNumber());
					ware.setMaterielOccupyNumber(0);
					ware.setMaterielWarnAmount(0);
					ware.setAllPrice(allPrice);
					double notaxNew = 0.00;
					
					if(IncludingTax == 0){
						taxNew = materiel.getMaterielStoragePrice();
						notaxNew = materiel.getMaterielStoragePrice()/1.16;
					}else{
						if (null==materiel.getMaterielStoragePrice()){
							notaxNew=0;
						}else {
							notaxNew = taxNew = materiel.getMaterielStoragePrice();
						}

					}
					ware.setMaterielTax(taxNew);
					ware.setMaterielNotax(notaxNew);
				}else {            //存在该物料的话  计算是否含税的费用更新含税单价和未含税单价
						List<Double> prices = CalculationTax.outStorageCalculationTax(ware.getMaterielNumber(),
							ware.getMaterielTax(), ware.getMaterielNotax(), 
							materiel.getMaterielNumber(), materiel.getMaterielStoragePrice(), IncludingTax);   //316.24
					ware.setMaterielTax(prices.get(1));
					ware.setMaterielNotax(prices.get(0));
					
					ware.setMaterielNumber(ware.getMaterielNumber()+materiel.getMaterielNumber());
				}
				if(null==ware.getId()||ware.getId().equals(0)) {     //如果没找到就是新增 执行insert
					erpWarehouseMapper.insert(ware);
				}else {                                               //找到执行更新
					erpWarehouseMapper.updateById(ware);
				}
				ErpMaterielFlowSummary mfs = new ErpMaterielFlowSummary();    //物料流转表增加一条信息  因为老刘不知道在哪查了这个表
				mfs.setMaterielId(ware.getId());
				mfs.setWarehouseId(materiel.getWarehouseId());
				mfs.setMaterielStorageNumber(materiel.getMaterielNumber());
				String id="QCWL"+IDUtils.genOrderId();    //加上00001
				ErpMaterielFlowSummary emfs=erpMaterielFlowSummaryMapper.selectBySheelId("'%"+id+"%'");
				if(emfs==null) {
					id=id+"00001";
				}else {
					String sheelId=emfs.getWorkSheetId().substring(12,emfs.getWorkSheetId().length());
					sheelId=IDUtils.addOne(sheelId);
					id=id+sheelId;
				}
				mfs.setWorkSheetId(id);
				
				mfs.setMaterielFlowDate(DataUtil.dateToStr(workDate));
				mfs.setMaterielStorageNumber(materiel.getMaterielNumber());
				mfs.setMaterielStoragePrice(materiel.getMaterielStoragePrice());
				mfs.setMaterielOutflowNumber(0);
				mfs.setMaterielOutflowPrice(0.0);
				if(faPiao.equals("商品普票")){
					mfs.setIncludingTax(1);
					materiel.setMaterielInvoiceType(1);
				}
				if(faPiao.equals("商品增值")){
					mfs.setIncludingTax(2);
					materiel.setMaterielInvoiceType(2);
				}
				if(faPiao.equals("服务普票")){
					mfs.setIncludingTax(3);
					materiel.setMaterielInvoiceType(3);
				}
				if(faPiao.equals("服务增值")){
					mfs.setIncludingTax(4);
					materiel.setMaterielInvoiceType(4);
				}
				if(faPiao.equals("运输发票")){
					mfs.setIncludingTax(5);
					materiel.setMaterielInvoiceType(5);
				}
				if(faPiao==null || faPiao.equals("无发票")){
					mfs.setIncludingTax(0);
					materiel.setMaterielInvoiceType(0);
				}
				mfs.setMaterielFlowType(0);
				mfs.setFlowSubject("期初物料");
				mfs.setMaterielSource("--");
				mfs.setMaterielWhereabouts(cangkuName);
				mfs.setOutWarehouseId(wareHouse.getWarehouseId());
				mfs.setFlowAttn(jingban);
				erpMaterielFlowSummaryMapper.insert(mfs);
				
				materiel.setMaterielDot("");
				//materiel.setMaterielStorageDate(DataUtil.dateToStr(workDate));
				materiel.setMaterielLoad(0);
				materiel.setMaterielRefurbished(0);
				materiel.setMaterielId(0);
				materiel.setMaterielFlowId(0);
				materiel.setState(3);
				materiel.setDelectType(1);
				materiel.setQichutype("期初");
				materiel.setKucunorliucun("库存");
				materiel.setFenzu(IDUtils.genItemId());
				materiel.setCustomerId(custId);
				ErpMaterielCopy copy=BlankUtil.copyMateriel(materiel);
				if(shengIds!=null&&shengIds.length>0) {    //判断有几个生产编号就在物料表插入几条数据

					for(int count=0;count<shengIds.length;count++) {
						if(shengIds.length>count&&!shengIds[count].equals("undefined")) {
							materiel.setMaterielProductionId(shengIds[count]);
							copy.setMaterielProductionId(shengIds[count]);
						}else{
							materiel.setMaterielProductionId("");
							copy.setMaterielProductionId("");
						}
						if(qrCode.length>count&&!qrCode[count].equals("undefined")) {
							materiel.setMaterielEqcode(qrCode[count]);
							copy.setMaterielEqcode(qrCode[count]);
						}else{
							materiel.setMaterielEqcode("");
							copy.setMaterielEqcode("");
						}
						if(rfList.length>count&&!rfList[count].equals("undefined")) {
							materiel.setMaterielRfid(rfList[count]);
							copy.setMaterielRfid(rfList[count]);
						}else{
							materiel.setMaterielRfid("");
							copy.setMaterielRfid("");
						}




						erpMaterielMapper.insert(materiel);
						copy.setMaterielId(materiel.getId());
						erpMaterielCopyMapper.insert(copy);
						ware.setMaterielId(materiel.getId());
						erpWarehouseMapper.updateById(ware);
						//addMaterielFlow(materiel,faPiao,taxNew);   出库的
						
						if(materiel.getZhiNeng()) {                         //是不是智能轮胎 如果是只能轮胎会带一条传感器的物料表数据   erp_materiel表里iszhi_neng=true表示是只能轮胎 对应的corresponding_id就是物料表里传感器的id istai表示是否是轮胎
							String[] sChuanList=chuanIds.split(",");
					    	String[] qrChuanList=qrChuanCodes.split(",");
					    	String[] rfChuanList=rfChuanIds.split(",");
					    	ma.setCorrespondingId(materiel.getId());
					    	ma.setMaterielStorageDate(materiel.getMaterielStorageDate());
					    	ma.setWarehouseId(materiel.getWarehouseId());
					    	if(sChuanList.length>count) {
					    		ma.setMaterielProductionId(sChuanList[count]);
					    	}else {
					    		ma.setMaterielProductionId("");
					    	}
					    	if(qrChuanList.length>count) {
					    		ma.setMaterielEqcode(qrChuanList[count]);
					    	}else {
					    		ma.setMaterielEqcode("");
					    	}
					    	if(rfChuanList.length>count) {
					    		ma.setMaterielRfid(rfChuanList[count]);
					    	}else {
					    		ma.setMaterielRfid("");
					    	}
					    	ma.setMaterielLoad(0);
					    	ma.setMaterielRefurbished(0);
					    	ma.setTai(false);
					    	ma.setMaterielInvoiceType(materiel.getMaterielInvoiceType());
					    	ma.setDelectType(0);
					    	ma.setCustomerId(custId);
					    	ma.setQichutype("期初");
							ma.setKucunorliucun("库存");
							ErpMaterielCopy copy1=BlankUtil.copyMateriel(ma);
							copy1.setCorrespondingId(copy.getId());
					    	erpMaterielMapper.insert(ma);                              //插入传感器数据
					    	copy1.setMaterielId(ma.getId());
					    	erpMaterielCopyMapper.insert(copy1);
					    	ware = new ErpWarehouse();
							ware.setCustomerId(custId);
							ware.setWarehouseId(materiel.getWarehouseId());
							ware.setMaterielName(ma.getMaterielName());
							ware.setMaterielBrand(ma.getMaterielBrand());
							ware.setMaterielSpecifications(ma.getMaterielSpecifications());
							ware.setMaterielModel(ma.getMaterielModel());
							ware.setMaterielPlace(ma.getMaterielPlace());
							ware.setMaterielState(ma.getMaterielState());
							ware.setMaterielUnit(ma.getMaterielUnit());
							ErpWarehouse ware1=erpWarehouseMapper.selectWareHouse(ware);
							if(ware1==null) {
								ware.setMaterielNumber(ma.getMaterielNumber());
								ware.setMaterielOccupyNumber(0);
								ware.setMaterielWarnAmount(0);
								ware.setAllPrice(allPrice);
								double notaxNew = 0.00;
								
								if(IncludingTax == 0){              //计算含税和未含税单价
									taxNew = ma.getMaterielStoragePrice();
									notaxNew = ma.getMaterielStoragePrice()/1.16;
								}else{
									if (null==ma.getMaterielStoragePrice()){
										notaxNew=0;
									}else {
										notaxNew = taxNew = ma.getMaterielStoragePrice();
									}
								}
								ware.setMaterielTax(taxNew);
								ware.setMaterielNotax(notaxNew);
								ware.setMaterielId(ma.getId());
								ware.setInvoiceType(faPiao);
								erpWarehouseMapper.insert(ware);                 //插入传感器仓库表数据
							}else {
								List<Double> prices = CalculationTax.outStorageCalculationTax(ware1.getMaterielNumber(),
										ware1.getMaterielTax(), ware1.getMaterielNotax(), 
										ma.getMaterielNumber(), ma.getMaterielStoragePrice(), IncludingTax);   //316.24
								ware1.setMaterielTax(prices.get(1));
								ware1.setMaterielNotax(prices.get(0));
								
								ware1.setMaterielNumber(ware1.getMaterielNumber()+ma.getMaterielNumber());
								erpWarehouseMapper.updateById(ware1);
							}
					    	materiel.setCorrespondingId(ma.getId());
					    	materiel.setMaterielTaiyaid(ma.getMaterielProductionId());
					    	copy.setCorrespondingId(copy1.getId());
					    	copy.setMaterielTaiyaid(copy1.getMaterielProductionId());
					    	erpMaterielMapper.updateAllColumnById(materiel);           //更新轮胎对应的传感器物料表id
					    	erpMaterielCopyMapper.updateAllColumnById(copy);


						}
						if(materiel.getMaterielName().indexOf("轮胎")!=-1||(materiel.getMaterielName().indexOf("轮胎")!=-1&&materiel.getTai())){        //如果是轮胎物料 在对应的轮胎记录表里添加数据
							addMaterielDown(materiel,id,custName,cangkuName,custId,workDate,ma);
						}
//						String sql ="select FORMAT(sum(materiel_storage_price) / count(1),2) materiel_storage_price from erp_materiel where warehouse_id ="+materiel.getWarehouseId()+" and materiel_name='"+materiel.getMaterielName().trim()+"' and materiel_brand='"+materiel.getMaterielBrand().trim()+"' and materiel_Specifications='"+materiel.getMaterielSpecifications().trim()+"' and materiel_model='"+materiel.getMaterielModel().trim()+"' and materiel_place='"+materiel.getMaterielPlace().trim()+"' and materiel_state='"+materiel.getMaterielState().trim()+"' and materiel_unit='"+materiel.getMaterielUnit().trim()+"' and delect_type=1";
//						List<Map<String, Object>> objlist= erpMaterielMapper.selectIn(sql);//判断原物料表有没有这个物料
//						if(objlist.get(0).get("materiel_storage_price")!=null) {
//							sql = " where warehouse_id =" + materiel.getWarehouseId() + " and materiel_name='" + materiel.getMaterielName().trim() + "' and materiel_brand='" + materiel.getMaterielBrand().trim() + "' and materiel_Specifications='" + materiel.getMaterielSpecifications().trim() + "' and materiel_model='" + materiel.getMaterielModel().trim() + "' and materiel_place='" + materiel.getMaterielPlace().trim() + "' and materiel_state='" + materiel.getMaterielState().trim() + "' and materiel_unit='" + materiel.getMaterielUnit().trim() + "' and delect_type=1";
//							erpMaterielMapper.updatedd(objlist.get(0).get("materiel_storage_price").toString(),sql);
//						}
						materiel.setId(null);
					}
					
				}else {
					erpMaterielMapper.insert(materiel);             //如果不是智能轮胎 直接插入物料数据
					if(pan) {               //更新仓库表里对应的物料表id
						ware.setMaterielId(materiel.getId());
						erpWarehouseMapper.updateById(ware);
					}
					//addMaterielFlow(materiel,faPiao,taxNew);              //增加物料流转表数据
					if(materiel.getMaterielName().indexOf("轮胎")!=-1||(materiel.getMaterielName().indexOf("轮胎")!=-1&&materiel.getTai())){       //如果是轮胎物料 在对应的轮胎记录表里添加数据
						addMaterielDown(materiel,id,custName,cangkuName,custId,workDate,null);          
					}
				}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Result<Integer>(1, e.getMessage());
		}
		return new Result<Integer>(0, 1);
	}
	
	/**
	 * 添加物料表下面的内容
	 * @param materiel
	 * @param id
	 * @param custName
	 * @param cangkuName
	 * @param custId
	 */
	public void addMaterielDown(ErpMateriel materiel,String id,String custName,String cangkuName,int custId,Date workDate,ErpMateriel ma) {
		
			
	    	ErpTireArchives ta = new ErpTireArchives();
	    	ta.setTireId(materiel.getId());
	    	ta.setTireTread1(0.0);
	    	ta.setTireTread2(0.0);
	    	ta.setTireTread3(0.0);
	    	ta.setTireTread4(0.0);
	    	erpTireArchivesMapper.insert(ta);
	    	
	    	ErpTireArchivesWork taw = new ErpTireArchivesWork();
	    	taw.setTireId(materiel.getId());
	    	taw.setWorkDate(workDate);
	    	taw.setWorkSheetId(id);
	    	ErpCustomer cust=erpCustomerMapper.selectById(custId);
	    	taw.setWorkServiceSector(cust.getCusName());
	    	if(materiel.getWarehouseId()!=null) {
	    		ErpCustomerWarehouse cw=erpCustomerWarehouseMapper.selectById(materiel.getWarehouseId());
	    		taw.setTireLocation(cust.getCusName()+"-"+cw.getWarName());
	    	}
	    	taw.setWorkMileage(0.0);
	    	taw.setWorkProject("期初物料");
	    	taw.setWorkTireState(materiel.getMaterielState());
	    	taw.setTireCost(materiel.getMaterielStoragePrice());
	    	taw.setTireState(materiel.getMaterielState());
			taw.setCustomerId(custId);
			taw.setCostType(0);
			taw.setCalculatingMileage(0);
			erpTireArchivesWorkMapper.insert(taw);
			
			ErpTireSensor tireSensor=new ErpTireSensor();
			tireSensor.setBt("1");
			tireSensor.setRimsId(0);
			tireSensor.setRimsPrice(0.0);
			if(ma!=null) {
				tireSensor.setSensorId(ma.getId());
				tireSensor.setSensorPrice(ma.getMaterielStoragePrice());
			}else {
				tireSensor.setSensorId(0);
				tireSensor.setSensorPrice(0.0);
			}
			tireSensor.setSensorId1(0);
			tireSensor.setTireId(materiel.getId());
			tireSensor.setTirePrice(materiel.getMaterielStoragePrice());
			tireSensor.setWarehouseId(materiel.getWarehouseId());
			erpTireSensorMapper.insert(tireSensor);
	}

	public void addMaterielFlow(ErpMateriel materiel,String faPiao,Double materielTax) {
		ErpMaterielFlowMateriel materielFlow=new ErpMaterielFlowMateriel();
		materielFlow.setMaterielFlowId(materiel.getId());
		materielFlow.setMaterielBrand(materiel.getMaterielBrand());
		materielFlow.setMaterielModel(materiel.getMaterielModel());
		materielFlow.setMaterielName(materiel.getMaterielName());
		materielFlow.setMaterielPlace(materiel.getMaterielPlace());
		materielFlow.setMaterielPrice(materiel.getMaterielStoragePrice());
		materielFlow.setMaterielProductionId(materiel.getMaterielProductionId());
		materielFlow.setMaterielSpecifications(materiel.getMaterielSpecifications());
		materielFlow.setMaterielState(materiel.getMaterielState());
		materielFlow.setMaterielTotal(materiel.getMaterielStoragePrice()*materiel.getMaterielNumber());
		materielFlow.setMaterielUnit(materiel.getMaterielUnit());
		materielFlow.setMaterielTotalTax(materiel.getMaterielNumber()*materielTax);
		materielFlow.setInvoiceType(faPiao);
		materielFlow.setMaterielNumber(materiel.getMaterielNumber());
		erpMaterielFlowMaterielMapper.insert(materielFlow);
	}
}
